import { defineStore } from "pinia";
import loginApi from "@/api/login";
import type { userInfoParams, loginData } from "@/api/login";
import { ElMessage } from "element-plus";

function initUserInfo() {
 return {
  password: "",
  phone: "",
  token: ""
 }
}

const userBaseInfo = defineStore("userBase", {
  state() {
    return {
      token: localStorage.getItem("TOKEN") || "",
      userInfo: initUserInfo(),
    };
  },
  actions: {
    // 登录
    async login(userInfo: userInfoParams) {
      try {
        let result = await loginApi.reqLogin(userInfo);
        // @ts-ignore
        this.token = result.data.token;
        // @ts-ignore
        localStorage.setItem("TOKEN", result.data.token);
        ElMessage({
          type: "success",
          message: "登录成功",
        });
        return "ok";
      } catch (error) {
        ElMessage.error("登录失败");
        return Promise.reject(error);
      }
    },

    async reset() {
      this.token = "";
      this.userInfo = initUserInfo();
      localStorage.removeItem("TOKEN");
    },
    //退出
    async logout() {
      try {
        await loginApi.reqLogOut();
        this.reset(); //清空信息
        // 清空路由
      } catch (error) {
        return Promise.reject(error);
      }
    },
  },
  getters: {},
});
export default userBaseInfo;
